﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AnesSystem.Models;
using System.Collections.ObjectModel;
using AnesSystem.Controls;
using AnesSystem.Services;
using System.Windows;
using Common;

namespace AnesSystem.ViewModels
{
    public class PacuEventAndDrugWinViewModel : BaseViewModel<PacuEventAndDrugWinViewModel>
    {
        #region Variables

        private EventAndDrug _eventAndDrug;
        private List<CustomEDBtnCtrl> _displayEventCtrlList;
        private Dictionary<string, List<ConfigEventsModel>> _eventList;
        private ObservableCollection<ConfigEventTypesModel> _eventTypeList;
        private Dictionary<string, List<CustomEDBtnCtrl>> _eventCtrlList;
        private ObservableCollection<CommonTypeCellCtrl> _eventTypeCtrlList;
        private List<ConfigEventsModel> _dropDownShowList;
        private CommonTypeCellCtrl _currentSelType;
        private string CurEventCode;
        //可用来判断是编辑与新增
        private bool _isAutoShow;
        //左边选择栏
        private bool _leftIsShow;
        //删除按钮
        private Visibility _delShow;
        //保存并继续
        private Visibility _SaveAndContinueShow;

        private static string status = Constants.SUCCESS;
        #endregion

        #region Constructor

        public PacuEventAndDrugWinViewModel()
        {
            _eventAndDrug = new EventAndDrug();
            _dropDownShowList = new List<ConfigEventsModel>();
            _currentSelType = new CommonTypeCellCtrl();
            _eventList = new Dictionary<string, List<ConfigEventsModel>>();
            _displayEventCtrlList = new List<CustomEDBtnCtrl>();
            _eventTypeCtrlList = new ObservableCollection<CommonTypeCellCtrl>();
            _eventTypeList = new ObservableCollection<ConfigEventTypesModel>();
            _eventCtrlList = new Dictionary<string, List<CustomEDBtnCtrl>>();
            InitialEventTypeList();
            InitialEventList();
            InitDropDownList();
            CreateEventTypeCtrlList();
            GetDisplayEventCtrlList(_eventTypeList.First().Code);
        }

        #endregion

        #region Properties

        public EventAndDrug EventAndDrug
        {
            get
            {
                if (_eventAndDrug == null)
                {
                    return new EventAndDrug();
                }
                return _eventAndDrug;
            }
            set
            {
                _eventAndDrug = value;
                RaisePropertyChanged("EventAndDrug");
            }
        }

        public ObservableCollection<CommonTypeCellCtrl> EventTypeCtrlList
        {
            get
            {
                return _eventTypeCtrlList;
            }

            set
            {
                _eventTypeCtrlList = value;
            }
        }

        public List<CustomEDBtnCtrl> DisplayEventCtrlList
        {
            get
            {
                return _displayEventCtrlList;
            }

            set
            {
                _displayEventCtrlList = value;
                RaisePropertyChanged("DisplayEventCtrlList");
            }
        }

        public CommonTypeCellCtrl CurrentSelType
        {
            get
            {
                return _currentSelType;
            }
            set
            {
                _currentSelType = value;
                GetDisplayEventCtrlList((value.Tag as ConfigEventTypesModel).Code);
                RaisePropertyChanged("CurrentSelType");
            }
        }

        public bool IsAutoShow
        {
            get
            {
                return _isAutoShow;
            }

            set
            {
                SetShowValue(value);
                _isAutoShow = value;
                RaisePropertyChanged("CurrentSelType");
            }
        }



        public bool LeftIsShow
        {
            get
            {
                return _leftIsShow;
            }

            set
            {
                _leftIsShow = value;
                RaisePropertyChanged("LeftIsShow");
            }
        }

        public Visibility DelShow
        {
            get
            {
                return _delShow;
            }

            set
            {
                _delShow = value;
                RaisePropertyChanged("DelShow");
            }
        }

        public Visibility SaveAndContinueShow
        {
            get
            {
                return _SaveAndContinueShow;
            }

            set
            {
                _SaveAndContinueShow = value;
                RaisePropertyChanged("SaveAndContinueShow");
            }
        }

        public List<ConfigEventsModel> DropDownShowList
        {
            get
            {
                return _dropDownShowList;
            }

            set
            {
                _dropDownShowList = value;
            }
        }

        private void SetShowValue(bool isShow)
        {
            if (isShow)
            {
                LeftIsShow = false;
                SaveAndContinueShow = Visibility.Collapsed;
                DelShow = Visibility.Visible;
            }
            else
            {
                LeftIsShow = true;
                SaveAndContinueShow = Visibility.Visible;
                DelShow = Visibility.Collapsed;
            }
        }





        #endregion

        #region 依赖属性

        #endregion

        #region Event

        #endregion

        #region Private Methods
        private void CreateEventTypeCtrlList()
        {
            foreach (var item in _eventTypeList)
            {
                CommonTypeCellCtrl ctrl = new CommonTypeCellCtrl();
                ctrl.PreviewMouseLeftButtonDown += Type_PreviewMouseLeftButtonDown;
                ctrl.Tag = item;
                ctrl.Display = item.Name;
                ctrl.Group = "group";
                ctrl.FontSize = 16;
                ctrl.Margin = new System.Windows.Thickness(20, 10, 0, 0);
                EventTypeCtrlList.Add(ctrl);
            }
        }



        private void InitialEventList()
        {
            var list = DataManager.Instance.ConfigEventsModelList.GroupBy(O => O.EventTypeCode);
            foreach (var item in list)
            {
                if (!string.IsNullOrEmpty(item.Key))
                    _eventList.Add(item.Key, item.ToList());
            }
        }

        private void InitialEventTypeList()
        {
            foreach (var item in DataManager.Instance.ConfigEventTypesModelList)
            {
                if (!string.IsNullOrEmpty(item.Code))
                    _eventTypeList.Add(item);
            }
        }
        public void InitDropDownList()
        {

            foreach (var item in DataManager.Instance.ConfigEventsModelList)
            {
                if (!IsShow(item))
                {
                    continue;
                }
                ConfigEventsModel cem = new ConfigEventsModel();
                cem = item.CloneObj<ConfigEventsModel>();
                cem.Name = GetEventDisplayName(item);
                DropDownShowList.Add(cem);
            }
        }

        private void GetDisplayEventCtrlList(string group)
        {
            if (!string.IsNullOrEmpty(group))
            {
                if (!_eventCtrlList.ContainsKey(group))
                {
                    List<ConfigEventsModel> list = _eventList[group];
                    List<CustomEDBtnCtrl> listCtrl = new List<CustomEDBtnCtrl>();
                    foreach (var item in list)
                    {
                        if (!IsShow(item))
                        {
                            continue;
                        }
                        CustomEDBtnCtrl ctrl = new CustomEDBtnCtrl();
                        ctrl.Clicked += Ctrl_Clicked;
                        ctrl.Margin = new System.Windows.Thickness(5);
                        ctrl.Tag = item;
                        ctrl.Display = GetEventDisplayName(item);
                        listCtrl.Add(ctrl);
                    }
                    _eventCtrlList.Add(group, listCtrl);
                    DisplayEventCtrlList = listCtrl;
                }
                else
                {
                    DisplayEventCtrlList = _eventCtrlList[group];
                }
            }
        }
       

        private string GetEventDisplayName(ConfigEventsModel item)
        {

            if (item.Single)
            {
                return item.Name;
            }
            List<PatientEventsModel> events = OperationDataPool.Instance.CurOperationData.EventDataCache.SearchEventExeByCode(item.Code);
            if (item.Name.Equals("入手术室") || item.Name.Equals("入复苏室"))
            {
                if (events != null && events.Count > 0)
                {
                    if (item.Equals("入手术室"))
                    {
                        return "出手术室";
                    }
                    else
                    {
                        return "出复苏室";
                    }
                }
                else
                {
                    return item.Name;
                }
            }
            else
            {
                string trueName = "";
                if (DataManager.Instance.Code2events.ContainsKey(item.Code))
                {
                    trueName = DataManager.Instance.Code2events[item.Code].Name;
                }
                if (events != null && events.Count > 0)
                {
                    events.Sort((PatientEventsModel o1, PatientEventsModel o2) =>
                    {
                        if (o1.BeginTime > o2.BeginTime)
                        {
                            return 1;
                        }
                        else if (o1.BeginTime < o2.BeginTime)
                        {
                            return -1;
                        }
                        else
                        {
                            return 0;
                        }
                    });

                    PatientEventsModel pEM = events.Last();
                    if (pEM.EndTime.Equals(new DateTime()))
                    {
                        return trueName + "结束";
                    }
                    else
                    {
                        return trueName + "开始";
                    }
                }
                else
                {
                    return trueName + "开始";
                }
            }
        }

        //进度条中的事件不在此显示
        private bool IsShow(ConfigEventsModel item)
        {
            if (item.Code.Equals(Constants.EVENT_IN_ROOM) || item.Code.Equals(Constants.EVENT_ANES) || item.Code.Equals(Constants.EVENT_OPERATION) || item.Code.Equals(Constants.EVENT_IN_HUIFUSHI))
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        private void Save2DB(PatientEventsModel pem)
        {
            pem.InputTime = DateTime.Now;
            PatientEventsService.Instance.AddUpdate(pem);
        }

        private void ChangedDisPlay()
        {
            PatientEventsModel pem = EventAndDrug.PatientEvents;
            string code = pem.Code;
            if (!string.IsNullOrEmpty(code))
            {
                if (code.Equals(Constants.EVENT_CTRL_REST) || code.Equals(Constants.EVENT_SUB_REST))
                {
                    if (DataManager.Instance.Code2events.ContainsKey(code))
                    {
                        ConfigEventsModel cem = DataManager.Instance.Code2events[code];
                        if (_eventCtrlList.ContainsKey(cem.EventTypeCode))
                        {
                            List<CustomEDBtnCtrl> list = _eventCtrlList[cem.EventTypeCode];
                            if (list != null && list.Count > 0)
                            {
                                foreach (var item in list)
                                {
                                    if (code.Equals(((ConfigEventsModel)item.Tag).Code))
                                    {
                                        item.Display = GetEventDisplayName(cem);
                                    }
                                }
                            }
                        }
                    }
                }
            }

        }

        private void Save()
        {
            if (CheckEnterValue())
            {
                ConfigEventsModel configEvent = DataManager.Instance.GetEventConfigByCode(CurEventCode);
                if (IsAutoShow)
                {
                    if (configEvent.Single)
                    {
                        OperationDataPool.Instance.CurOperationData.EventDataCache.DelEvent(EventAndDrug.PatientEvents);
                        EventAndDrug.PatientEvents.BeginTime = EventAndDrug.Time;
                        EventAndDrug.PatientEvents.EndTime = EventAndDrug.Time;
                        if (EventAndDrug.IsEdit)
                        {
                            if (DataManager.Instance.Name2events.ContainsKey(EventAndDrug.Name))
                            {
                                EventAndDrug.PatientEvents.Code = DataManager.Instance.Name2events[EventAndDrug.Name].Code;
                            }

                        }
                        Save2DB(EventAndDrug.PatientEvents);
                    }
                    else if (EventAndDrug.IsEnd)
                    {
                        EventAndDrug.PatientEvents.EndTime = EventAndDrug.Time;
                        Save2DB(EventAndDrug.PatientEvents);
                        ChangeEventTime(true);
                    }
                    else
                    {
                        EventAndDrug.PatientEvents.BeginTime = EventAndDrug.Time;
                        Save2DB(EventAndDrug.PatientEvents);
                        ChangeEventTime(false);
                    }
                    EventAndDrug.PatientEvents.InputTime = DateTime.Now;
                    OperationDataPool.Instance.CurOperationData.EventDataCache.AddUpdateEvent(EventAndDrug.PatientEvents);
                }
                else if (configEvent.Single)
                {
                    EventAndDrug.PatientEvents.Code = configEvent.Code;
                    EventAndDrug.PatientEvents.BeginTime = EventAndDrug.Time;
                    EventAndDrug.PatientEvents.EndTime = EventAndDrug.Time;
                    EventAndDrug.PatientEvents.PatientID = DataManager.Instance.CurrentPatientLink.Id.ToString();
                    EventAndDrug.PatientEvents.InputTime = DateTime.Now;
                    Save2DB(EventAndDrug.PatientEvents);
                    OperationDataPool.Instance.CurOperationData.EventDataCache.AddUpdateEvent(EventAndDrug.PatientEvents);
                }
                else
                {
                    string code = configEvent.Code;
                    List<PatientEventsModel> eventList = GetSortEventsByCode(CurEventCode);
                    PatientEventsModel oldEvent = null;
                    if (eventList != null && eventList.Count > 0)
                    {
                        oldEvent = eventList.Last();
                    }
                    if (oldEvent == null || !oldEvent.EndTime.Equals(new DateTime()))
                    {
                        EventAndDrug.PatientEvents.Code = configEvent.Code;
                        EventAndDrug.PatientEvents.BeginTime = EventAndDrug.Time;
                        EventAndDrug.PatientEvents.PatientID = DataManager.Instance.CurrentPatientLink.Id.ToString();
                        EventAndDrug.PatientEvents.InputTime = DateTime.Now;
                        Save2DB(EventAndDrug.PatientEvents);
                        OperationDataPool.Instance.CurOperationData.EventDataCache.AddUpdateEvent(EventAndDrug.PatientEvents);
                        ChangeEventTime(false);
                    }
                    else
                    {
                        oldEvent.EndTime = EventAndDrug.Time;
                        EventAndDrug.PatientEvents = oldEvent;
                        EventAndDrug.PatientEvents.InputTime = DateTime.Now;
                        Save2DB(EventAndDrug.PatientEvents);
                        OperationDataPool.Instance.CurOperationData.EventDataCache.AddUpdateEvent(EventAndDrug.PatientEvents);
                        ChangeEventTime(true);
                    }
                }
                status = Constants.SUCCESS;
            }
            else
            {
                status = Constants.FAILED;
            }
        }
        private void ChangeEventTime(bool isEnd)
        {
            if (CurEventCode.Equals(Constants.EVENT_IN_ROOM) && !isEnd)
            {
                DataManager.Instance.CurrentPatientLink.Status.InRoomTime = EventAndDrug.PatientEvents.BeginTime;
                DateTime inRoomTime = EventAndDrug.PatientEvents.BeginTime;
                DateTime anesRecordStartTime = inRoomTime.AddMinutes(-inRoomTime.Minute % 15);
                DataManager.Instance.CurrentPatientLink.Status.AnesRecordStartTime = anesRecordStartTime;
            }
            else if (CurEventCode.Equals(Constants.EVENT_IN_ROOM) && isEnd)
            {
                DataManager.Instance.CurrentPatientLink.Status.OutRoomTime = EventAndDrug.PatientEvents.EndTime;
            }
            else if (CurEventCode.Equals(Constants.EVENT_IN_HUIFUSHI) && !isEnd)
            {
                DataManager.Instance.CurrentPatientLink.Status.InPacuTime = EventAndDrug.PatientEvents.BeginTime;
                DateTime inPacuTime = DataManager.Instance.CurrentPatientLink.Status.InPacuTime;
                DateTime pacuStartTime = inPacuTime.AddMinutes(-inPacuTime.Minute % 15);
                DataManager.Instance.CurrentPatientLink.Status.PacuStartTime = pacuStartTime;
            }
            else if (CurEventCode.Equals(Constants.EVENT_IN_HUIFUSHI) && isEnd)
            {
                DataManager.Instance.CurrentPatientLink.Status.OutPacuTime = EventAndDrug.PatientEvents.EndTime;
                DataManager.Instance.CurrentPatientLink.Application.Detailstatus = Constants.OR_STATUS_FLAG_OUT_PCU;

            }

            else if (CurEventCode.Equals(Constants.EVENT_ANES))
            {
                if (isEnd)
                {
                    DataManager.Instance.CurrentPatientLink.Status.MazuiEndTime = EventAndDrug.PatientEvents.EndTime;
                }
                else
                {
                    DataManager.Instance.CurrentPatientLink.Status.MazuiStartTime = EventAndDrug.PatientEvents.BeginTime;
                }
            }
            else if (CurEventCode.Equals(Constants.EVENT_OPERATION))
            {
                if (isEnd)
                {
                    DataManager.Instance.CurrentPatientLink.Status.OperEndTime = EventAndDrug.PatientEvents.EndTime;
                }
                else
                {
                    DataManager.Instance.CurrentPatientLink.Status.OperStartTime = EventAndDrug.PatientEvents.BeginTime;
                }
            }
            else if (CurEventCode.Equals(Constants.EVENT_CTRL_REST))
            {
                OperationDataPool.Instance.CurOperationData.VitalSignDataCache.RefreshRespEvent();
            }
            else if (CurEventCode.Equals(Constants.EVENT_SUB_REST))
            {
                OperationDataPool.Instance.CurOperationData.VitalSignDataCache.RefreshRespEvent();
            }
            SaveOper2DB();
            PacuProcessViewModel.Instance.ChangeEvent(CurEventCode, isEnd);
        }

        /// <summary>
        /// 检验事件输入信息
        /// </summary>
        /// <returns></returns>
        private bool CheckEnterValue()
        {
            EventAndDrug.Time = EventAndDrug.Time.AddSeconds(-EventAndDrug.Time.Second).AddMilliseconds(-EventAndDrug.Time.Millisecond);
            if (string.IsNullOrEmpty(EventAndDrug.Name))
            {
                MessageBoxCommon.ShowDialog("事件名称不能为空!", MessageBoxCommon.OK);
                return false;
            }
            DateTime inPacuTime = DataManager.Instance.CurrentPatientLink.Status.InPacuTime;
            DateTime outPacuTime = DataManager.Instance.CurrentPatientLink.Status.OutPacuTime;
            if (!inPacuTime.Equals(new DateTime()))
            {
                if (EventAndDrug.Time < inPacuTime && !EventAndDrug.Name.Equals("入复苏室"))
                {
                    MessageBoxCommon.ShowDialog("开始时间应大于等于入复苏室时间!", MessageBoxCommon.OK);
                    return false;
                }
                if (!outPacuTime.Equals(new DateTime()))
                {
                    if (EventAndDrug.Time > outPacuTime && !EventAndDrug.Name.Equals("出复苏室"))
                    {
                        MessageBoxCommon.ShowDialog("开始时间应小于等于出复苏室时间!", MessageBoxCommon.OK);
                        return false;
                    }
                }
            }
            ConfigEventsModel configEvent = null;
            if (DataManager.Instance.Name2events.ContainsKey(GetRealEventName(EventAndDrug.Name)))
            {
                configEvent = DataManager.Instance.Name2events[GetRealEventName(EventAndDrug.Name)];
            }
            if (configEvent != null)
            {
                CurEventCode = configEvent.Code;
            }
            else
            {
                CurEventCode = InsertEvent2Cache(EventAndDrug.Name.Trim());
            }
            if (configEvent == null || configEvent.Single || configEvent.Code.Equals(Constants.EVENT_IN_ROOM))
            {
                return true;
            }
            List<PatientEventsModel> eventList = GetSortEventsByCode(CurEventCode);
            PatientEventsModel oldEvent = null;
            if (eventList != null && eventList.Count > 0)
            {
                oldEvent = eventList.Last();

            }
            if (oldEvent == null)
            {
                return true;
            }
            if (IsAutoShow)
            {
                if (EventAndDrug.IsEnd)
                {
                    if ((EventAndDrug.Time - oldEvent.BeginTime).TotalMinutes <= 0)
                    {
                        MessageBoxCommon.ShowDialog("结束时间应大于开始时间!", MessageBoxCommon.OK);
                        return false;
                    }
                }
                else
                {
                    if (!oldEvent.EndTime.Equals(new DateTime()))
                    {
                        if ((EventAndDrug.Time - oldEvent.EndTime).TotalMinutes >= 0)
                        {
                            MessageBoxCommon.ShowDialog("开始时间应小于结束时间!", MessageBoxCommon.OK);
                            return false;
                        }
                    }
                }
            }
            //新增
            else
            {
                if (oldEvent.EndTime.Equals(new DateTime()))
                {
                    if ((EventAndDrug.Time - oldEvent.BeginTime).TotalMinutes <= 0)
                    {
                        MessageBoxCommon.ShowDialog("结束时间应大于开始时间!", MessageBoxCommon.OK);
                        return false;
                    }
                }
            }
            return true;
            //已结束
            //if (!oldEvent.EndTime.Equals(new DateTime()))
            //{
            //    if (!CurEventCode.Equals(Constants.EVENT_IN_ROOM))
            //    {
            //        //编辑
            //        if (IsAutoShow)
            //        {
            //            if (!EventAndDrug.IsEnd)
            //            {
            //                if ((oldEvent.EndTime - EventAndDrug.Time).TotalMinutes <= 0)
            //                {
            //                    MessageBoxCommon.ShowDialog("开始时间应大于结束时间!", MessageBoxCommon.OK);
            //                    return false;
            //                }
            //                if ((oldEvent.EndTime - EventAndDrug.Time).TotalMinutes <= 5)
            //                {
            //                    MessageBoxCommon.ShowDialog("与结束时间间隔过小，应大于5分钟!", MessageBoxCommon.OK);
            //                    return false;
            //                }
            //            }
            //            else
            //            {
            //                if ((EventAndDrug.Time - oldEvent.BeginTime).TotalMinutes <= 0)
            //                {
            //                    MessageBoxCommon.ShowDialog("结束时间应大于开始时间!", MessageBoxCommon.OK);
            //                    return false;
            //                }
            //                if ((EventAndDrug.Time - oldEvent.BeginTime).TotalMinutes <= 5)
            //                {
            //                    MessageBoxCommon.ShowDialog("与开始时间间隔过小，应大于5分钟!", MessageBoxCommon.OK);
            //                    return false;
            //                }
            //            }
            //        }
            //        return true;
            //    }

            //    return true;
            //}
            ////未结束
            //else
            //{
            //    if (!CurEventCode.Equals(Constants.EVENT_IN_ROOM))
            //    {
            //        //编辑
            //        if (IsAutoShow)
            //        {
            //            if ((oldEvent.EndTime - EventAndDrug.Time).TotalMinutes <= 0)
            //            {
            //                MessageBoxCommon.ShowDialog("开始时间应大于结束时间!", MessageBoxCommon.OK);
            //                return false;
            //            }
            //            if ((oldEvent.EndTime - EventAndDrug.Time).TotalMinutes <= 5)
            //            {
            //                MessageBoxCommon.ShowDialog("与结束时间间隔过小，应大于5分钟!", MessageBoxCommon.OK);
            //                return false;
            //            }
            //        }
            //        else
            //        {
            //            if ((EventAndDrug.Time - oldEvent.BeginTime).TotalMinutes <= 0)
            //            {
            //                MessageBoxCommon.ShowDialog("结束时间应大于开始时间!", MessageBoxCommon.OK);
            //                return false;
            //            }
            //            if ((EventAndDrug.Time - oldEvent.BeginTime).TotalMinutes <= 5)
            //            {
            //                MessageBoxCommon.ShowDialog("与开始时间间隔过小，应大于5分钟!", MessageBoxCommon.OK);
            //                return false;
            //            }
            //        }
            //    }
            //    return true;
            //}

        }

        private void CloseWin()
        {
            if (status.Equals(Constants.SUCCESS))
            {
                DrugAndEventWindow.Instance.CloseWin(false);
            }
        }

        private string InsertEvent2Cache(string text)
        {
            ConfigEventsModel newEvent = new ConfigEventsModel();
            newEvent.Code = text;
            newEvent.Name = text;
            newEvent.EventTypeCode = "eventType_2";
            newEvent.Deleted = false;
            newEvent.Position = 0;
            newEvent.Single = true;
            DataManager.Instance.AddOneEvent(newEvent);
            return newEvent.Code;
        }

        /// <summary>
        /// 获取事件真实名字
        /// </summary>
        /// <param name="commond"></param>
        private string GetRealEventName(string name)
        {
            if (name.EndsWith("开始"))
            {
                return name.Replace("开始", " ").Trim();
            }
            else if (name.EndsWith("结束"))
            {
                return name.Replace("结束", " ").Trim();
            }
            else if (name.Equals("入手术室") || name.Equals("出手术室"))
            {
                return "入手术室";
            }
            else if (name.Equals("入复苏室") || name.Equals("出复苏室"))
            {
                return "入复苏室";
            }
            else
            {
                return name.Trim();
            }

        }
        private List<PatientEventsModel> GetSortEventsByCode(string code)
        {
            List<PatientEventsModel> eventList = OperationDataPool.Instance.CurOperationData.EventDataCache.SearchEventExeByCode(code);
            if (eventList != null || eventList.Count > 0)
            {
                eventList.Sort((PatientEventsModel o1, PatientEventsModel o2) =>
                {
                    if (o1.BeginTime > o2.BeginTime)
                    {
                        return 1;
                    }
                    else if (o1.BeginTime < o2.BeginTime)
                    {
                        return -1;
                    }
                    else
                    {
                        return 0;
                    }
                });
                return eventList;
            }
            else
            {
                return null;
            }
        }
        #endregion


        #region Public/Protected Methods

        public void Excute(string commond)
        {
            switch (commond)
            {
                case "Save":
                    Save();
                    RefreshWin();
                    CloseWin();
                    RefreshDisplayName();
                    break;
                case "SaveAndContinue":
                    Save();
                    RefreshWin();
                    RefreshDisplayName();
                    EventAndDrug = new EventAndDrug();
                    break;
                case "DelEvent":
                    Delete();
                    RefreshWin();
                    CloseWin();
                    RefreshDisplayName();

                    break;
                case "Cancel":
                    status = Constants.SUCCESS;
                    CloseWin();
                    break;
            }
        }

        private void Delete()
        {
            string code = EventAndDrug.PatientEvents.Code;
            CurEventCode = code;
            bool isEnd = EventAndDrug.IsEnd;
            if (code.Equals(Constants.EVENT_IN_ROOM))
            {
                if (EventAndDrug.Name.Equals("入手术室"))
                {
                    MessageBoxCommon.ShowDialog("入手术室事件不能删除!", MessageBoxCommon.OK);
                    return;
                }
                else
                {
                    MessageBoxCommon.ShowDialog("出手术室事件不能删除!", MessageBoxCommon.OK);
                    return;
                }
            }
            if (code.Equals(Constants.EVENT_IN_ROOM))
            {
                if (EventAndDrug.Name.Equals("入复苏室"))
                {
                    MessageBoxCommon.ShowDialog("入复苏室事件不能删除!", MessageBoxCommon.OK);
                    status = Constants.FAILED;
                    return;
                }
                else
                {
                    MessageBoxCommon.ShowDialog("出复苏室事件不能删除!", MessageBoxCommon.OK);
                    status = Constants.FAILED;
                    return;
                }
            }
            if (DataManager.Instance.Code2events.ContainsKey(code))
            {
                ConfigEventsModel cem = DataManager.Instance.Code2events[code];
                if (cem.Single)
                {
                    EventAndDrug.PatientEvents.Deleted = true;
                    OperationDataPool.Instance.CurOperationData.EventDataCache.DelEvent(EventAndDrug.PatientEvents);
                }
                else
                {
                    if (CurEventCode.Equals(Constants.EVENT_ANES) || CurEventCode.Equals(Constants.EVENT_OPERATION))
                    {
                        if (isEnd)
                        {
                            EventAndDrug.PatientEvents.EndTime = new DateTime();
                            OperationDataPool.Instance.CurOperationData.EventDataCache.AddUpdateEvent(EventAndDrug.PatientEvents);
                        }
                        else
                        {
                            EventAndDrug.PatientEvents.Deleted = true;
                            OperationDataPool.Instance.CurOperationData.EventDataCache.DelEvent(EventAndDrug.PatientEvents);
                        }
                        ChangeStatus(code);
                    }
                    if (CurEventCode.Equals(Constants.EVENT_CTRL_REST) || CurEventCode.Equals(Constants.EVENT_SUB_REST))
                    {
                        if (isEnd)
                        {
                            EventAndDrug.PatientEvents.EndTime = new DateTime();
                            OperationDataPool.Instance.CurOperationData.EventDataCache.AddUpdateEvent(EventAndDrug.PatientEvents);
                        }
                        else
                        {
                            EventAndDrug.PatientEvents.Deleted = true;
                            OperationDataPool.Instance.CurOperationData.EventDataCache.DelEvent(EventAndDrug.PatientEvents);
                        }
                        OperationDataPool.Instance.CurOperationData.VitalSignDataCache.RefreshRespEvent();
                    }
                }
            }

            PacuProcessViewModel.Instance.ChangeEvent(code, isEnd);
            Save2DB(EventAndDrug.PatientEvents);
            status = Constants.SUCCESS;

        }

        private void ChangeStatus(string code)
        {
            if (code.Equals(Constants.EVENT_ANES))
            {
                DataManager.Instance.CurrentPatientLink.Status.MazuiStartTime = new DateTime();
                DataManager.Instance.CurrentPatientLink.Status.MazuiEndTime = new DateTime();
                DataManager.Instance.CurrentPatientLink.Status.MazuiSpanTime = 0;
                SaveOper2DB();
            }
            if (code.Equals(Constants.EVENT_OPERATION))
            {
                DataManager.Instance.CurrentPatientLink.Status.OperStartTime = new DateTime();
                DataManager.Instance.CurrentPatientLink.Status.OperEndTime = new DateTime();
                DataManager.Instance.CurrentPatientLink.Status.OperSpanTime = 0;
                SaveOper2DB();
            }

        }

        private void SaveOper2DB()
        {
            PatientLinkService.Instance.AddUpdate(DataManager.Instance.CurrentPatientLink);
        }

        public void RefreshWin()
        {
            //刷新事件一栏
            for (int i = 1; i <= DataManager.Instance.CurrentPatientLink.Status.PacuPage; i++)
            {
                (DataManager.Instance.PacuRecordCtrl.DataContext as PacuRecordCtrlViewModel).PacuRecordCtrlViewModels[i].PacuEventAndMedicineCtrlViewModel.Refresh();
            }
            //刷新标记一栏
            for (int i = 1; i <= DataManager.Instance.CurrentPatientLink.Status.PacuPage; i++)
            {
                (DataManager.Instance.PacuRecordCtrl.DataContext as PacuRecordCtrlViewModel).PacuRecordCtrlViewModels[i].PacuOperStatusItemCtrlViewModel.Refresh();
            }

        }

        public void RefreshDisplayName()
        {
            List<string> changeCodeList = new List<string>();
            changeCodeList.Add(Constants.EVENT_CTRL_REST);
            changeCodeList.Add(Constants.EVENT_SUB_REST);
            changeCodeList.Add(Constants.EVENT_IN_HUIFUSHI);
            foreach (var code in changeCodeList)
            {
                if (DataManager.Instance.Code2events.ContainsKey(code))
                {
                    ConfigEventsModel cem = DataManager.Instance.Code2events[code];
                    foreach (var item in DropDownShowList)
                    {
                        if (item.Code.Equals(code))
                        {
                            item.Name = GetEventDisplayName(item);
                        }
                    }
                    if (_eventCtrlList.ContainsKey(cem.EventTypeCode))
                    {
                        List<CustomEDBtnCtrl> list = _eventCtrlList[cem.EventTypeCode];
                        if (list != null && list.Count > 0)
                        {
                            foreach (var item in list)
                            {
                                if (code.Equals(((ConfigEventsModel)item.Tag).Code))
                                {
                                    item.Display = GetEventDisplayName(cem);
                                }
                            }
                        }
                    }
                }
            }
        }

        public List<ConfigEventsModel> GetDisPlayEvents()
        {
            List<ConfigEventsModel> list = new List<ConfigEventsModel>();
            foreach (var item in DataManager.Instance.ConfigEventsModelList)
            {
                if (!IsShow(item))
                {
                    continue;
                }
                ConfigEventsModel cem = new ConfigEventsModel();
                item.CloneObj<ConfigEventsModel>();
                cem.Name = GetEventDisplayName(item);
                list.Add(cem);
            }
            return list;
        }

        #endregion

        #region EventHandlers

        private void Type_PreviewMouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            CommonTypeCellCtrl type = sender as CommonTypeCellCtrl;
            GetDisplayEventCtrlList((type.Tag as ConfigEventTypesModel).Code);
        }

        private void Ctrl_Clicked(object sender, EventArgs e)
        {
            CustomEDBtnCtrl ctrl = sender as CustomEDBtnCtrl;
            ConfigEventsModel cem = ctrl.Tag as ConfigEventsModel;
            CurEventCode = cem.Code;
            EventAndDrug.Name = ctrl.Display;
            PatientEventsModel pem = new PatientEventsModel();
            pem.Code = cem.Code;
            pem.BeginTime = EventAndDrug.Time;
            pem.PatientID = DataManager.Instance.CurrentPatientLink.Id.ToString();
            EventAndDrug.PatientEvents = pem;
            EventAndDrug.IsEdit = IsEdit(pem.Code);
        }
        private bool IsEdit(string code)
        {
            if (code.Equals(Constants.EVENT_ANES) || code.Equals(Constants.EVENT_IN_ROOM) || code.Equals(Constants.EVENT_OPERATION) || code.Equals(Constants.EVENT_SUB_REST)
               || code.Equals(Constants.EVENT_IN_HUIFUSHI) || code.Equals(Constants.EVENT_CTRL_REST))
            {
                return false;
            }
            else
            {
                return true;
            }
        }



        #endregion
    }
}
